<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
date_default_timezone_set ( 'prc' );
set_time_limit(0);
require_once (dirname ( __FILE__ ) . "/../../PHPExcel/PHPExcel.php");
class Order extends CI_Controller {
	public function __construct() {
		parent::__construct ();
		if (! $this->session->userdata ( 'logged_in' )) {
			redirect ( 'passport/index' );
			exit ();
		}
	}
	/*
	 * 返回订单列表
	 */
	public function index() {
		$state = $this->uri->segment(4);
		if(!isset($state)){//没有传值时默认为-1
    		$state=-1;
    	}
		$phone = $this->uri->segment(6);
		if(empty($phone)){
    		$phone="empty";
    	}
		$data ['state']=$state;
		$this->load->library ( 'pagination' );
		// 每页显示数据条数
		$per_page = 20;//暂定为20条

		$config ['base_url'] = site_url ( 'order/index/state/'.$state.'/phone/'.$phone);
		$this->load->model ( 'order_model' );

		if($phone=="empty"){//这里是为了搜索
    		$phone=null;
    	}
		// 数据总数
		$config ['total_rows'] = $this->order_model->count_orders ($state,$phone);

		// $config ['total_rows']=200;
		$config ['per_page'] = $per_page;
		$config ['first_link'] = '第一页';
		$config ['last_link'] = '最后一页';
		$config ['next_link'] = '下一页';
		$config ['prev_link'] = '上一页';
		$config ['uri_segment'] = 7;

		$this->pagination->initialize ( $config );
		$data ['links'] = $this->pagination->create_links ();
		// 偏移量
		$offset = intval ( $this->uri->segment (7) );
		$data ['orders'] = $this->order_model->get_orders($state,$phone,$per_page, $offset );
		$data ['start'] = getSdate();
		$data ['end'] = getEdate();
		$this->load->model ( 'config_model' );
		$config = $this->config_model->find_by_key ("state");
		$data ['orderstate']=$config['value'];
		$data ['title'] = '订单列表 - '.SYSTEM_NAME;
		$this->load->view ( 'header', $data );
		$this->load->view ( 'order/index' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 返回订单详情
	 */
	public function detail() {
		$id = $this->uri->segment ( 4 );
		$this->load->model ( 'order_model' );
		$order= $this->order_model->load ( $id );
		$data ['order'] =$order;
		$this->load->model ( 'orderdetail_model' );
		$data ['orderdetails'] = $this->orderdetail_model->find_by_order ( $id );
		$data ['title'] = '订单详情 - '.SYSTEM_NAME;
		$this->load->view ( 'header', $data );
		$this->load->view ( 'order/detail' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 删除订单详情(订单总额未考虑)
	 */
	public function deleteDetail() {
		$id = $this->input->post ( 'id' );
		$this->load->model ( 'orderdetail_model' );
		if($this->orderdetail_model->delete ( $id )){
			return_json ( TRUE, '', '删除成功！' );
		}else{
			return_json ( FALSE, '', '删除失败！' );
		}
	}
	/*
	 * 删除订单信息
	 */
	public function delete() {
	    $id = $this->input->post('id');
		$this->load->model ( 'order_model' );
		$neworder =array(
			'del'=>1
		);
    	if ($this->order_model->update($id,$neworder)) {
    		return_json ( TRUE, '', '删除成功！' );
    	}else{
    		return_json ( FALSE, '', '删除失败！' );
    	}
    }
	/*
	 * 恢复订单信息
	 */
	public function recover() {
	    $id = $this->input->post('id');
		$this->load->model ( 'order_model' );
		$neworder =array(
			'del'=>0
		);
    	if ($this->order_model->update($id,$neworder)) {
    		return_json ( TRUE, '', '恢复成功！' );
    	}else{
    		return_json ( FALSE, '', '恢复失败！' );
    	}
    }
	/*
	 *设置订单状态
	 */
	public function setOrderstate() {
		$state=$this->input->post ( 'state' );
		$this->load->model ( 'config_model' );
		$config = $this->config_model->find_by_key ("state");
		$newconfig = array (
			'value' => $state
		);
		$this->config_model->update ( $config['id'], $newconfig );
		return_json(TRUE,'','设置成功！');
	}
	/*
	 *一键操作功能(定时功能：先完成订单，再确认订单，修改用户状态)(暂时没用)
	 */
	public function oneclick() {
		$state = $this->input->post ( 'state' );
		$this->load->model ( 'user_model' );
		$this->load->model ( 'order_model' );
		$orderdate= $this->common->getOrderDate();
		if($state==1){//确认订单时
			$users = $this->user_model->find_unorder_users ();
			foreach($users as $user){
				$this->createOrder($user['id'],$user['school'],$orderdate);
			}
			$this->user_model->update_users ();
		}
		$this->order_model->update_orders($state);
		return_json ( TRUE, '', '操作成功！' );
	}
	/*
	 * 一键发送短信提醒(暂时没用)
	 */
	public function remind(){
		$this->load->model ( 'user_model' );
		$this->load->model ( 'order_model' );
		$users = $this->user_model->find_all_user ();
		foreach($users as $user){
			$order = $this->order_model->find_by_user ($user['id']);
			if(empty($order)&&!empty($user['phone'])){
				$this->sendMessage($user['id']);
			}
		}
		return_json ( TRUE, '', '发送成功！' );
	}
	/*
	 * 导出订单统计(旧方法)
	 */
	public function exportOldOrders() {
		$sdate = $this->uri->segment(4);
		$edate = $this->uri->segment(6);
		$resultPHPExcel = new PHPExcel ();
		$objActSheet = $resultPHPExcel->getActiveSheet();
		$this->load->model ( 'product_model' );
		$this->load->model ( 'order_model' );
		$this->load->model ( 'school_model' );
		$schools = $this->school_model->find_all_school ();
		$i=1;
		for($start = strtotime($sdate); $start <= strtotime($edate);$start += 3600*24){
			  $objActSheet->setCellValue ( 'A'.$i, '配送日期：'.date ( "Y-m-d", $start));
			  $i++;
			  foreach ( $schools as $school ) {
			  		$products = $this->order_model->count_by_date_school (date ( "Y-m-d", $start), $school['id']);
				  	$str="";
				  	foreach($products as $product){
						$str=$str.$product['name'].'：'.$product['sum'].'份 ';
					}
				  	$objActSheet->setCellValue ( 'A'.$i,$school['name']. '：'.$str);
					$i++;
					$classes = $this->school_model->find_class_by_schoolid ($school['id']);
					foreach($classes as $class){
						$products = $this->order_model->count_by_date_class (date ( "Y-m-d", $start), $class['id']);
						$str="";
				  		foreach($products as $product){
							$str=$str.$product['name'].'：'.$product['sum'].'份 ';
						}
						$objActSheet->setCellValue ( 'A'.$i,$class['gname'].$class['name']. '：'.$str);
						$i++;
					}
			  }
			  $totalproducts = $this->order_model->count_by_date (date ( "Y-m-d", $start));
			  $str="";
			  foreach($totalproducts as $product){
				   $str=$str.$product['name'].'：'.$product['sum'].'份 ';
			  }
			  $objActSheet->setCellValue ( 'A'.$i, '总计：'.$str);
			  $i+=2;
		}

		$outputFileName = '订单统计.xls';
		$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
		// ob_start(); ob_flush();
		header ( "Content-Type: application/force-download" );
		header ( "Content-Type: application/octet-stream" );
		header ( "Content-Type: application/download" );
		header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
		header ( "Content-Transfer-Encoding: binary" );
		header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
		header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
		header ( "Pragma: no-cache" );
		$xlsWriter->save ( "php://output" );
	}
	/*
	 * 导出订单统计(旧方法)
	 */
	public function exportOrders() {
		$sdate = $this->uri->segment(4);
		$edate = $this->uri->segment(6);
		$resultPHPExcel = new PHPExcel ();
		$objActSheet = $resultPHPExcel->getActiveSheet();
		$this->load->model ( 'product_model' );
		$this->load->model ( 'order_model' );
		$this->load->model ( 'school_model' );
		$schools = $this->school_model->find_all_school ();
	    foreach ( $schools as $key=>$school ) {
			$i=1;
			if($key>0){
				$resultPHPExcel->createSheet();
				$resultPHPExcel->setactivesheetindex($key);
		  	}
	      	$objActSheet = $resultPHPExcel->getActiveSheet();
	      	$objActSheet->setTitle($school['name']); //设置工作表名称
	      	for($start = strtotime($sdate); $start <= strtotime($edate);$start += 3600*24){
				$objActSheet->setCellValue ( 'A'.$i, '配送日期：'.date ( "Y-m-d", $start));
			  	$i++;
			  	$classes = $this->school_model->find_class_by_schoolid ($school['id']);
			  	foreach($classes as $class){
					$products = $this->order_model->count_by_date_class (date ( "Y-m-d", $start), $class['id']);
					$str="";
		  			foreach($products as $product){
						$str=$str.$product['name'].'：'.$product['sum'].'份 ';
					}
					$objActSheet->setCellValue ( 'A'.$i,$class['gname'].$class['name']. '：'.$str);
					$i++;
			 	 }
			 	 $products = $this->order_model->count_by_date_school (date ( "Y-m-d", $start), $school['id']);
		  	 	 $str="";
		  	 	 foreach($products as $product){
					$str=$str.$product['name'].'：'.$product['sum'].'份 ';
			  	}
			  	$objActSheet->setCellValue ( 'A'.$i,'总计：'.$str);
			  	$i+=2;
		  	}
		}
		$resultPHPExcel->setActiveSheetIndex(0);
		$outputFileName = '订单统计.xls';
		$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
		// ob_start(); ob_flush();
		header ( "Content-Type: application/force-download" );
		header ( "Content-Type: application/octet-stream" );
		header ( "Content-Type: application/download" );
		header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
		header ( "Content-Transfer-Encoding: binary" );
		header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
		header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
		header ( "Pragma: no-cache" );
		$xlsWriter->save ( "php://output" );
	}
	/*
	 * 导出订单统计(新方法)
	 */
	public function exportNewOrders() {
		$sdate = $this->uri->segment(4);
		$edate = $this->uri->segment(6);
		$this->load->model ( 'school_model' );
		$this->load->model ( 'user_model' );
		$this->load->model ( 'order_model' );
		$this->load->model ( 'cookbook_model' );
		$schoolid=$this->session->userdata ( 'schoolid' );
		$school = $this->school_model->load ($schoolid);
		$weekarray=array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");
		$resultPHPExcel = new PHPExcel ();
		$objActSheet = $resultPHPExcel->getActiveSheet();
      	$objActSheet->setTitle($school['name']); //设置工作表名称
      	$total = $this->user_model->count_by_school ($school['id']);
      	$grades=$this->school_model->find_grade_by_type($school['type']);
		foreach($grades as $key=>$grade){
			$grades[$key]['sum']=$this->user_model->count_by_school_grade ($school['id'],$grade['id']);
		}
		$i=1;
      	for($start = strtotime($sdate); $start <= strtotime($edate);$start += 3600*24){
      		$date=date ( "Y-m-d", $start);
		 	$temp = $this->cookbook_model->count_by_school_date_type ($school['id'],$date,-1);
			if(empty($temp)){
				continue;
			}
			$objActSheet->setCellValue ( 'A'.$i, '配送日期：'.$date.'('.$weekarray[date ( "w", $start)].')');
			$i++;
			$objActSheet->setCellValue ( 'A'.$i, '总计：');
		  	$i++;
			for($j=1;$j<=3;$j++){
				$products = $this->order_model->sum_by_date_school_type ($date, $school['id'],$j);
				if(empty($products)){
					continue;
				}
				$sum=$total;
				$others=array();
				foreach($products as $key=>$product){
					$objActSheet->setCellValue ( 'A'.$i,$product['name'].'：'.$product['sum'].'份 ');
					$k='D';
					foreach($grades as $key2=>$grade){
						$result = $this->order_model->sum_by_date_school_type_grade ($date, $school['id'],$j,$grade['id'],$product['id']);
						if(empty($result['sum'])){
							$result['sum']=0;//为空时填0
						}
						$objActSheet->setCellValue ( $k.$i,$grade['name'].'：'.$result['sum'].'份 ');
						if(!isset($others[$key2]['total'.$product['id']])){
							$others[$key2]['total'.$product['id']]=$result['sum'];
						}else{
							$others[$key2]['total'.$product['id']]=$others[$key2]['total'.$product['id']]+$result['sum'];
						}
						$k++;
					}
					$sum-=$product['sum'];
					$i++;
			  	}
				$objActSheet->setCellValue ( 'A'.$i,'默认：'.$sum.'份 ');
				$k='D';
				foreach($grades as $key=>$grade){
					$defalut=$grade['sum'];
					$other=$others[$key];
					foreach($other as $item){
						$defalut=$defalut-intval($item);
					}
					$objActSheet->setCellValue ( $k.$i,$grade['name'].'：'.$defalut.'份 ');
					$k++;
				}
				$i+=2;
			}  	 	
	  	}
		$objActSheet->getColumnDimension ( 'D' )->setWidth ( 13 );
		$objActSheet->getColumnDimension ( 'E' )->setWidth ( 13 );
		$objActSheet->getColumnDimension ( 'F' )->setWidth ( 13 );
		$outputFileName = '订单统计表.xls';
		$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
		// ob_start(); ob_flush();
		header ( "Content-Type: application/force-download" );
		header ( "Content-Type: application/octet-stream" );
		header ( "Content-Type: application/download" );
		header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
		header ( "Content-Transfer-Encoding: binary" );
		header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
		header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
		header ( "Pragma: no-cache" );
		$xlsWriter->save ( "php://output" );
	}
	/*
	 * 订餐统计页面
	 */
	public function export() {
		$sdate = $this->uri->segment(4);
		$edate = $this->uri->segment(6);
		$this->load->model ( 'school_model' );
		$this->load->model ( 'user_model' );
		$this->load->model ( 'order_model' );
		$this->load->model ( 'cookbook_model' );
		$schoolid=$this->session->userdata ( 'schoolid' );
		$school = $this->school_model->load ($schoolid);
		$weekarray=array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");
		$results=array();
      	$total = $this->user_model->count_by_school ($school['id']);
      	$grades=$this->school_model->find_grade_by_type($school['type']);
		foreach($grades as $key=>$grade){
			$grades[$key]['sum']=$this->user_model->count_by_school_grade ($school['id'],$grade['id']);
		}
      	for($start = strtotime($sdate); $start <= strtotime($edate);$start += 3600*24){
		 	$date=date ( "Y-m-d", $start);
		 	$temp = $this->cookbook_model->count_by_school_date_type ($school['id'],$date,-1);
			if(empty($temp)){
				continue;
			}
			$row=array();
			$title=array();
			$title[]='配送日期：'.$date.'('.$weekarray[date ( "w", $start)].')';
			$title[]='总计：';
			$content=array();
			for($j=1;$j<=3;$j++){
				$products = $this->order_model->sum_by_date_school_type ($date, $school['id'],$j);
				if(empty($products)){
					continue;
				}
				$sum=$total;
				$others=array();
				foreach($products as $key=>$product){
					$str=array();
					$str[]=$product['name'].'：'.$product['sum'].'份 ';
					foreach($grades as $key2=>$grade){
						$result = $this->order_model->sum_by_date_school_type_grade ($date, $school['id'],$j,$grade['id'],$product['id']);
						if(empty($result['sum'])){
							$result['sum']=0;//为空时填0
						}
						$str[]=$grade['name'].'：'.$result['sum'].'份 ';
						if(!isset($others[$key2]['total'.$product['id']])){
							$others[$key2]['total'.$product['id']]=$result['sum'];
						}else{
							$others[$key2]['total'.$product['id']]=$others[$key2]['total'.$product['id']]+$result['sum'];
						}
					}
					$content[]=$str;
					$sum-=$product['sum'];
			  	}
				$str2=array();
				$str2[]='默认：'.$sum.'份 ';
				foreach($grades as $key=>$grade){
					$defalut=$grade['sum'];
					$other=$others[$key];
					foreach($other as $item){
						$defalut=$defalut-intval($item);
					}
					$str2[]=$grade['name'].'：'.$defalut.'份 ';
				}
				$content[]=$str2;
			}
			$row['title']=$title;
			$row['content']=$content;
			$results[]=$row;
	  	}
		$data ['results']=$results;
		$data ['title'] = '订餐统计 - '.SYSTEM_NAME;
		$this->load->view ( 'header', $data );
		$this->load->view ( 'order/export' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 导出学生订餐表
	 */
	public function exportUserOrders() {
		$sdate = $this->uri->segment(4);
		$edate = $this->uri->segment(6);
		$resultPHPExcel = new PHPExcel ();
		$objActSheet = $resultPHPExcel->getActiveSheet();
		$this->load->model ( 'school_model' );
		$this->load->model ( 'user_model' );
		$this->load->model ( 'order_model' );
		$weekarray=array("周日","周一","周二","周三","周四","周五","周六");
		$mealarray=array(1=>"早餐",2=>"中餐",3=>"晚餐");
		$schoolid=$this->session->userdata ( 'schoolid' );
		//$schoolid=20;
		$classes = $this->school_model->find_class_by_school_grade ($schoolid,-1);
	    foreach ( $classes as $key=>$class ) {
			if($key>0){
				$resultPHPExcel->createSheet();
				$resultPHPExcel->setactivesheetindex($key);
		  	}
	      	$objActSheet = $resultPHPExcel->getActiveSheet();
	      	$objActSheet->setTitle($class['gname'].$class['name']); //设置工作表名称
	      	$objActSheet->setCellValue ( 'A1', '序号');
			$objActSheet->setCellValue ( 'B1', '年级');
			$objActSheet->setCellValue ( 'C1', '班级');
			$objActSheet->setCellValue ( 'D1', '姓名');
			$a='E';
			$newdate=array();
			for($start = strtotime($sdate); $start <= strtotime($edate);$start += 3600*24){
				$date=date ( "Y-m-d", $start);
				$week=date ( "w", $start);
				$meal=array();
				for($j=1;$j<=3;$j++){
					$num = $this->order_model->count_by_date_type_school ($date,$j,$schoolid);//不应该用order
					if(empty($num)){
						continue;
					}
					$objActSheet->setCellValue ( $a.'1', $weekarray[$week].$mealarray[$j]);
					$a++;
					$meal[]=$j;
				}
				$data['date']=$date;
				$data['meal']=$meal;
				$newdate[]=$data;
			}
			//$newdate=array_unique($newdate);
			$i=2;
			$users = $this->user_model->find_by_class ($class['id']);
			foreach($users as $user){
				$objActSheet->setCellValue ( 'A'.$i, $i-1);
				$objActSheet->setCellValue ( 'B'.$i,$class['gname']);
				$objActSheet->setCellValue ( 'C'.$i,$class['name']);
				$objActSheet->setCellValue ( 'D'.$i,$user['sname']);
				$k='E';
				
				foreach($newdate as $data){
					foreach($data['meal'] as $meal){
						$product = $this->order_model->find_by_user_date ($user['id'],$data['date'],$meal);
						if(!empty($product)){
							$objActSheet->setCellValue ($k.$i, $product['name']);
						}else{
							$objActSheet->setCellValue ( $k.$i, '默认');
						}
						$k++;
					}
				}
				$i++;
			}
			$objActSheet->getColumnDimension ( 'A' )->setWidth ( 5 );
			$objActSheet->getColumnDimension ( 'B' )->setWidth ( 5 );
			$objActSheet->getColumnDimension ( 'C' )->setWidth ( 5 );
			$objActSheet->getColumnDimension ( 'D' )->setWidth ( 11 );
			$objActSheet->getColumnDimension ( 'E' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'F' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'G' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'H' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'I' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'J' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'K' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'L' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'M' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'N' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'O' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'P' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'Q' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'R' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'S' )->setWidth ( 9 );
		}
		$resultPHPExcel->setActiveSheetIndex(0);
		$outputFileName = '学生订餐表.xls';
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');  
        header('Content-Disposition: attachment;filename="'.$outputFileName.'');  
        header('Cache-Control: max-age=0');
		$objWriter = PHPExcel_IOFactory::createWriter($resultPHPExcel, "Excel5");  
		$objWriter->save('php://output');
		/*
		$outputFileName = '学生订餐表.xls';
		$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
		// ob_start(); ob_flush();
		header ( "Content-Type: application/force-download" );
		header ( "Content-Type: application/octet-stream" );
		header ( "Content-Type: application/download" );
		header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
		header ( "Content-Transfer-Encoding: binary" );
		header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
		header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
		header ( "Pragma: no-cache" );
		$xlsWriter->save ( "php://output" );*/
	}
	/*
	 * 导出学生订餐表(新)
	 */
	public function exportUserOrders2() {
		$sdate = $this->uri->segment(4);
		$edate = $this->uri->segment(6);
		$resultPHPExcel = new PHPExcel ();
		$objActSheet = $resultPHPExcel->getActiveSheet();
		$this->load->model ( 'school_model' );
		$this->load->model ( 'user_model' );
		$this->load->model ( 'order_model' );
		$this->load->model ( 'cookbook_model' );
		$weekarray=array("周日","周一","周二","周三","周四","周五","周六");
		$mealarray=array(1=>"早餐",2=>"中餐",3=>"晚餐");
		$schoolid=$this->session->userdata ( 'schoolid' );
		//$schoolid=20;
		$classes = $this->school_model->find_class_by_school_grade ($schoolid,-1);
	    foreach ( $classes as $key=>$class ) {
			if($key>0){
				$resultPHPExcel->createSheet();
				$resultPHPExcel->setactivesheetindex($key);
		  	}
	      	$objActSheet = $resultPHPExcel->getActiveSheet();
	      	$objActSheet->setTitle($class['gname'].$class['name']); //设置工作表名称
	      	$i=1;
			$objActSheet->setCellValue ( 'A'.$i, '订餐日期：'.date ( "n月d日", strtotime($sdate)).'至'.date ( "n月d日", strtotime($edate)));
			$i++;
	      	$objActSheet->setCellValue ( 'A'.$i, '序号');
			$objActSheet->setCellValue ( 'B'.$i, '年级');
			$objActSheet->setCellValue ( 'C'.$i, '班级');
			$objActSheet->setCellValue ( 'D'.$i, '姓名');
			$a='E';
			for($start = strtotime($sdate); $start <= strtotime($edate);$start += 3600*24){
				$date=date ( "Y-m-d", $start);
				$week=date ( "w", $start);
				for($j=1;$j<=3;$j++){
					$num = $this->cookbook_model->count_by_school_date_type ($schoolid,$date,$j);
					if(empty($num)){
						continue;
					}
					$objActSheet->setCellValue ( $a.$i, $weekarray[$week].$mealarray[$j]);
					$a++;
				}
			}
			//$newdate=array_unique($newdate);
			$i++;
			$users = $this->user_model->find_by_class ($class['id']);
			foreach($users as $user){
				$objActSheet->setCellValue ( 'A'.$i, $i-1);
				$objActSheet->setCellValue ( 'B'.$i,$class['gname']);
				$objActSheet->setCellValue ( 'C'.$i,$class['name']);
				$objActSheet->setCellValue ( 'D'.$i,$user['sname']);
				$k='E';
				$products=$this->order_model->find_by_user_dates($user['id'],$sdate,$edate);
				if(!empty($products)){
					foreach($products as $product){
						$objActSheet->setCellValue ($k.$i, $product['name']);
						$k++;
					}
				}else{
					for($j=$k;$j<$a;$j++){
						$objActSheet->setCellValue ($j.$i, '默认');
					}
				}
				$i++;
			}
			$objActSheet->getColumnDimension ( 'A' )->setWidth ( 5 );
			$objActSheet->getColumnDimension ( 'B' )->setWidth ( 5 );
			$objActSheet->getColumnDimension ( 'C' )->setWidth ( 5 );
			$objActSheet->getColumnDimension ( 'D' )->setWidth ( 11 );
			$objActSheet->getColumnDimension ( 'E' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'F' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'G' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'H' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'I' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'J' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'K' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'L' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'M' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'N' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'O' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'P' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'Q' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'R' )->setWidth ( 9 );
			$objActSheet->getColumnDimension ( 'S' )->setWidth ( 9 );
		}
		$resultPHPExcel->setActiveSheetIndex(0);
		$outputFileName = '学生订餐表.xls';
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');  
        header('Content-Disposition: attachment;filename="'.$outputFileName.'');  
        header('Cache-Control: max-age=0');
		$objWriter = PHPExcel_IOFactory::createWriter($resultPHPExcel, "Excel5");  
		$objWriter->save('php://output');
		/*
		$outputFileName = '学生订餐表.xls';
		$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
		// ob_start(); ob_flush();
		header ( "Content-Type: application/force-download" );
		header ( "Content-Type: application/octet-stream" );
		header ( "Content-Type: application/download" );
		header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
		header ( "Content-Transfer-Encoding: binary" );
		header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
		header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
		header ( "Pragma: no-cache" );
		$xlsWriter->save ( "php://output" );*/
	}
	/*
	 * 学生订餐信息页面
	 */
	public function export2() {
		$sdate = $this->uri->segment(4);
		$edate = $this->uri->segment(6);
		$this->load->model ( 'school_model' );
		$this->load->model ( 'user_model' );
		$this->load->model ( 'order_model' );
		$this->load->model ( 'cookbook_model' );
		$weekarray=array("周日","周一","周二","周三","周四","周五","周六");
		$mealarray=array(1=>"早餐",2=>"中餐",3=>"晚餐");
		$schoolid=$this->session->userdata ( 'schoolid' );
		//$schoolid=20;
		$classes = $this->school_model->find_class_by_school_grade ($schoolid,-1);
		$results=array();
	    foreach ( $classes as $key=>$class ) {
	    	$result=array();
			$title="订餐日期：".date ( "n月d日", strtotime($sdate))."至".date ( "n月d日", strtotime($edate));
			$row=array();
			$row[]="序号";
			$row[]="年级";
			$row[]="班级";
			$row[]="姓名";
			$meal_num=0;//订餐数
			for($start = strtotime($sdate); $start <= strtotime($edate);$start += 3600*24){
				$date=date ( "Y-m-d", $start);
				$week=date ( "w", $start);
				for($j=1;$j<=3;$j++){
					$num = $this->cookbook_model->count_by_school_date_type ($schoolid,$date,$j);
					if(empty($num)){
						continue;
					}
					$row[]=$weekarray[$week].$mealarray[$j];
					$meal_num++;
				}
			}
			$result[]=$row;
			$users = $this->user_model->find_by_class ($class['id']);
			$i=1;
			foreach($users as $user){
				$row=array();
				$row[]=$i;
				$row[]=$class['gname'];
				$row[]=$class['name'];
				$row[]=$user['sname'];
				$products=$this->order_model->find_by_user_dates($user['id'],$sdate,$edate);
				if(!empty($products)){
					foreach($products as $product){
						$row[]=$product['name'];
					}
				}else{
					for($j=0;$j<$meal_num;$j++){
						$row[]='默认';
					}
				}
				$result[]=$row;
				$i++;
			}
			$content['title']=$title;
			$content['result']=$result;
			$results[]=$content;
		}
		$data ['results']=$results;
		$data ['title'] = '学生订餐信息 - '.SYSTEM_NAME;
		$this->load->view ( 'header', $data );
		$this->load->view ( 'order/export2' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 导出配送单(暂时没用)
	 */
	public function exportOrderdetails() {
		$sdate = $this->uri->segment(4);
		$edate = $this->uri->segment(6);
		$resultPHPExcel = new PHPExcel ();
		$this->load->model ( 'order_model' );
		$this->load->model ( 'school_model' );
		$schools = $this->school_model->find_all_school ();
		$activeindex=0;//当前表格序号
		for($start = strtotime($sdate); $start <= strtotime($edate);$start += 3600*24){
		  $temp= $this->order_model->find_by_date(date ( "Y-m-d", $start));
		  if(empty($temp)){
		  	continue;
		  }
		  foreach ( $schools as $school ) {
		  	$a=0;
		  	if($activeindex>0){
				$resultPHPExcel->createSheet();
				$resultPHPExcel->setactivesheetindex($activeindex);
			}
			$objActSheet = $resultPHPExcel->getActiveSheet();
		  	$classes = $this->school_model->find_class_by_schoolid ($school['id']);

			foreach($classes as $class){
			$x=$a*47;
			if($x==0){
				$x=1;
			}
			$orders = $this->order_model->find_by_date_class (date ( "Y-m-d", $start), $class['id']);
			//设置当前活动sheet的名称
			//$objActSheet->setTitle('订单');
			$objActSheet->setCellValue ( 'A'.$x, '配送日期：'.date ( "Y-m-d", $start) );
			$objActSheet->setCellValue ( 'A'.($x+1), '学校：'.$class['sname'] );
			$objActSheet->setCellValue ( 'A'.($x+2), '班级：'.$class['gname'].$class['name'] );
			$str="";
			$products = $this->order_model->count_by_date_class (date ( "Y-m-d", $start), $class['id']);
			foreach($products as $product){
				$str=$str.$product['name'].'：'.$product['sum'].'份 ';
			}
			$objActSheet->setCellValue ( 'A'.($x+3),'套餐：'.$str);
			$i=4;
			$y=$x+$i;
			$j=1;
			$objActSheet->setCellValue ( 'A'.($x+$i), '序号' );
			$objActSheet->setCellValue ( 'B'.($x+$i), '学号' );
			$objActSheet->setCellValue ( 'C'.($x+$i), '姓名' );
			$objActSheet->setCellValue ( 'D'.($x+$i), '商品名称' );
			$objActSheet->setCellValue ( 'E'.($x+$i), '数量' );
			$objActSheet->getRowDimension(8)->setRowHeight(18);
			$i++;
			foreach ( $orders as $order ) {
				$objActSheet->setCellValue ( 'A' .($x+$i),$j);
				$objActSheet->setCellValue ( 'B' .($x+$i), $order['sno']);
				$objActSheet->setCellValue ( 'C' .($x+$i), $order ['sname'] );
				$objActSheet->setCellValue ( 'D' .($x+$i), $order ['name'] );
				$objActSheet->setCellValue ( 'E' .($x+$i), $order ['amount'] );
				$i++;
				$j ++;
			}
			$objActSheet->getStyle('A'.$i)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);//合计右对齐
			$styleArray = array(//加入边框
					'borders' => array(
							'allborders' => array(
									'style' => PHPExcel_Style_Border::BORDER_THIN
							),
					),
			);
			$objActSheet->getStyle('A'.$y.':E'.($x+$i-1))->applyFromArray($styleArray);
			/*
			//左对齐
			$objActSheet->getStyle ( 'A8:A' .($j+7) )->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_CENTER );
			$objActSheet->getStyle ( 'D8:D' .($j+7) )->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_CENTER );
			$objActSheet->getStyle ( 'E8:G' .($j+7) )->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_RIGHT );
			$objActSheet->getStyle ( 'B8:C' .($j+7) )->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_LEFT );

			$objActSheet->getStyle ( 'A8:G' .($j+8) )->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);//垂直居中
			*/
			$objActSheet->getHeaderFooter()->setOddFooter('&B&C第&P页,共&N页');
			$a++;
			}
			$objActSheet->getColumnDimension ( 'A' )->setWidth ( 5 );
			$objActSheet->getColumnDimension ( 'B' )->setWidth ( 20);
			$objActSheet->getColumnDimension ( 'C' )->setWidth ( 10 );
			$objActSheet->getColumnDimension ( 'D' )->setWidth ( 25 );
			$objActSheet->getColumnDimension ( 'E' )->setWidth ( 5 );
			$activeindex++;

		  }
		}
		$outputFileName = '配送单.xls';
		$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
		// ob_start(); ob_flush();
		header ( "Content-Type: application/force-download" );
		header ( "Content-Type: application/octet-stream" );
		header ( "Content-Type: application/download" );
		header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
		header ( "Content-Transfer-Encoding: binary" );
		header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
		header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
		header ( "Pragma: no-cache" );
		$xlsWriter->save ( "php://output" );
	}
	/*
	 * 生成默认订单
	 */
	private function createOrder($userid,$schoolid,$orderdate) {
		$this->load->model ( 'order_model' );
		$this->load->model ( 'orderdetail_model' );
		$this->load->model ( 'cookbook_model' );
		$orderno = build_order_no ($userid);
		$order = array (
			'orderno' => $orderno,
			'userid' => $userid,
			'order_time' => date ( "Y-m-d H:i:s" ),
			'total' => 0,
			'state' => 0
		);
		$orderid=$this->order_model->create ( $order );
		if (!empty($orderid)) {//插入的新数据ID不为空
			foreach($orderdate as $item){
				for($i=1;$i<=3;$i++){
					$product=$this->cookbook_model->find_product_by_date_type($schoolid,$item,$i);
					if(empty($product)){
						continue;
					}
					$orderdetail=array (
						'orderid' => $orderid,
						'productid' => $product['id'],
						'price' => $product['price'],
						'amount' => 1,
						'date' =>$item,
						'type' =>$i
					);
					//date('Y-m-d',strtotime($item))
					$this->orderdetail_model->create ( $orderdetail );
				}
			}
		}
	}
	/*
	 *发送短信提醒给用户
	 */
	public function sendMessage($userid) {
		$this->load->model ( 'user_model' );
		$user=$this->user_model->load ( $userid );
		$sid=SID;
		$appid=APPID;
		$key=KEY;
		$time=date("YmdHis").'111';
		$sign=md5($sid.$time.$key);
		$templateid=TEMPID;
		$param="";
		$phone = $user['phone'];
		$url="http://www.ucpaas.com/maap/sms/code?sid=".$sid."&appId=".$appid."&time=".$time."&sign=".$sign."&to=".$phone."&templateId=".$templateid."&param=".$param;
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, $url );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_HEADER, 0 );
		$output = curl_exec ( $ch );
		curl_close ( $ch );
		$output = json_decode($output);
		if($output->resp->respCode=="000000"){//短信发送成功
			$message = array (
					'phone' => $phone,
					'state' => 1,
					'smsid' => $output->resp->templateSMS->smsId,
					'createdate' => $output->resp->templateSMS->createDate
			);
			$this->load->model ( 'message_model' );
			$this->message_model->create($message);//更新短信表
		}
	}
}
